﻿using System;
using System.Linq;
using System.Web.Mvc;
using Mailias.UI.Web.Infrastructure;
using Raven.Client;
using Raven.Client.Embedded;

namespace Mailias.UI.Web
{
    public class MailiasDocumentStore
    {
        private static IDocumentStore _instance;

        public static IDocumentStore Instance
        {
            get
            {
                if (_instance == null)
                {
                    throw new InvalidOperationException("IDocumentStore has not been initialized");
                }
                return _instance;
            }
        }

        public static IDocumentStore Initialize(string dataDirectory)
        {
#if DEBUG
            _instance = new EmbeddableDocumentStore { DataDirectory = dataDirectory, UseEmbeddedHttpServer = true};
#else
            _instance = new EmbeddableDocumentStore {DataDirectory = dataDirectory};
#endif
            _instance.Conventions.IdentityPartsSeparator = "-";
            _instance.Initialize();
            return _instance;
        }
    }

    public class BaseDocumentStoreController : Controller
    {
        public IDocumentSession DocumentSession { get; set; }
        
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.IsChildAction)
            {
                return;
            }
            this.DocumentSession = MailiasDocumentStore.Instance.OpenSession();
            base.OnActionExecuting(filterContext);
        }

        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (filterContext.IsChildAction)
            {
                return;
            }
            if(this.DocumentSession != null && filterContext.Exception == null)
            {
                this.DocumentSession.SaveChanges();
            }
            this.DocumentSession.Dispose();
            base.OnActionExecuted(filterContext);
        }

    }
}